import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import config from '@/config'
export default createStore({
	state: {
		isLogin: false, //当前用户是否登录
		token: localStorage.getItem("token") || "",
		Login_dialog_flag: false, //登录弹框开关
		request_url: config.baseUrl, //项目请求接口地址(环境自适应)
		Horizontal_screen: false, //是否是宽屏
		Userdata: JSON.parse(localStorage.getItem("Userdata") || "{}"),//用户数据
		is_sync: true, //是否开启多个云手机的同步功能
		try_out_dialog_close: JSON.parse(localStorage.getItem("try_out_dialog_close") || 'false'),
		forceShowFreePhoneDialog: false, // 确保这个状态存在
		Phone_Local_keyboard_flag: JSON.parse(localStorage.getItem("Phone_Local_keyboard_flag") || 'true')//云手机各种状态本地存储控制表
	},
	mutations: {
		isLogin_fun(state) {
			if (state.token.startsWith('eyJ') && state.token) { // 简单判断是否是 JWT
				state.isLogin = true
			} else {
				// const data = JSON.parse(state.token); // 尝试解析 JSON
				if (localStorage.getItem("token")) {
					state.isLogin = true
				} else {
					console.log(state.token);
				}
			}
		},
		//用户数据存储
		localStorage_userdata(state, userdata) {
			state.Userdata = userdata;
			localStorage.setItem('Userdata', JSON.stringify(userdata))
		},
		//改变群控同步操作的开关
		change_is_sync(state, data) {
			state.is_sync = data
		},
		//改变屏幕是横屏还是竖屏
		change_screen(state, data) {
			state.Horizontal_screen = data
		},
		//当前用户是否登录
		no_login(state) {
			state.isLogin = false
		},
		//登录弹框显示
		Login_dialog_show(state) {
			state.Login_dialog_flag = true
		},
		//关闭体验试用弹窗
		setForceShowFreePhoneDialog(state, value) {
			state.forceShowFreePhoneDialog = value
		},
		updateTryOutDialogClose(state, data) {
			state.try_out_dialog_close = data
			window.localStorage.setItem('try_out_dialog_close', JSON.stringify(data))
		},
		//本地键盘还是云手机键盘状态控制
		Update_Local_keyboard_flag(state, data) {
			state.Phone_Local_keyboard_flag = data
		},
		//登录弹框隐藏
		Login_dialog_hide(state) {
			state.Login_dialog_flag = false
		}
	},
	actions: {
		// 将 API 调用移到 actions 中
		async updateLocalKeyboard({ commit }, payload) {
			const { udid, data } = payload;
			const request = (await import('@/utils')).default;

			try {
				const requestData = { udid: udid, type: data ? 'local' : 'phone' }
				await request.post('/tools/switch_local_keyboard', requestData)
				commit('Update_Local_keyboard_flag', data)
			} catch (error) {
				console.error('切换键盘失败:', error)
			}
		}
	},
	plugins: [
		createPersistedState({
			paths: ['Userdata', 'Phone_Local_keyboard_flag'] // 指定需要持久化的状态
		})
	],
	getters: {
	}
})